package com.hongtech.framework.aspect;

import com.alibaba.fastjson.JSON;
import com.hongtech.common.bean.Token;
import com.hongtech.common.util.SpringUtil;
import com.hongtech.common.util.TokenUtil;
import com.hongtech.framework.anno.OperateLog;
import com.hongtech.modules.system.entity.SysLogEntity;
import com.hongtech.modules.system.service.SysLogService;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 正常业务日志记录切面实现
 */
@Aspect
@Component
public class OperateLogAdvice {

    public static final Logger logger = Logger.getLogger(OperateLogAdvice.class);

    @Pointcut("@annotation(com.hongtech.framework.anno.OperateLog)")
    public void controllerAspect() {

    }

    /**
     * 当方法正常返回是执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes != null ? requestAttributes.getRequest() :null;
        if(request == null) return;
        OperateLog operateLog = method.getAnnotation(OperateLog.class);
        Token st = TokenUtil.getToken(request);
        if (ObjectUtils.isNotEmpty(operateLog)) {
            SysLogEntity sysLogEntity = new SysLogEntity();
            sysLogEntity.setTitle(operateLog.value());
            sysLogEntity.setUserName((st != null) ? st.getUname() : "system");
            sysLogEntity.setUrl(request.getRequestURI());
            sysLogEntity.setParams(JSON.toJSONString(request.getParameterMap()));
            SpringUtil.getBean(SysLogService.class).save(sysLogEntity);
            logger.debug("记录日志:" + sysLogEntity.toString());
        }
    }

}
